﻿#include <thirdparty/fist-log.h>

#include <utility>

#include "network_interface.h"
#include "network_peer.h"

using namespace asio;

CNetworkPeer::CNetworkPeer(INetworkManager* network, io_service* io_service, std::string ip, uint16_t port)
    : CNetworkNode(network, io_service)
    , m_ip(std::move(ip))
    , m_port(port)
    , m_try_connect(false)
{
    
}

CNetworkPeer::~CNetworkPeer()
{
    
}

void CNetworkPeer::Connect()
{
    if (valid() || m_try_connect) {
        return;
    }

    auto& sk = sock();
    if (sk.is_open()) {
        sk.close();
    }
    
    m_try_connect = true;
    auto ed = ip::tcp::endpoint(ip::address::from_string(m_ip), m_port);
    sk.async_connect(ed, [&, this]<typename ErrorCode>(ErrorCode && code) {
        m_try_connect = false;
        set_valid(code.value() == 0);
        if (code) {
            LOG_ERROR("connect ip:{}, port:{} fail. err:{}, msg:{}", m_ip.c_str(), m_port, code.value(), 
                code.message().c_str());
        } else {
            LOG_INFO("connect successful. ip:{}, port:{}", m_ip.c_str(), m_port);
            PostRead();
        }
    });
}

bool CNetworkPeer::canDel()
{
    return false;
}
